<template>

    <div class="app-content">
      <div class="list" v-if="!list.loading">
            <template v-if="!$util.isEmpty(list.data)">
                      <div class="staff-list_box">
						  <checkbox-group  @change="checkItem">
            <div class="staff-list"
                    v-for="(item,index) in list.data"
                @click="toDetail(item)"
                :key="index"
                >
                <checkbox :checked="item.check" color="#ffd11a" :value="item.relation_id+''" v-if="option.isSelect == 'true'" :data-index="index"/>
                <img :src="item.user_picture" alt="">
                <div class="staff-list_right">
                    <h3>{{item.name}}</h3>
                    <div>职位：{{item.job}}</div>
                    <div>部门：{{item.department_name}}</div>
                    <div>电话：{{item.mobile_phone}}</div>
                </div>
                <div class="staff-status">
                    <img v-if="item.status===1" class="staff-status" :src="imgUrl+'publicicon/icon_memconcle.png'" alt="">
                    <img v-if="item.status===2" class="staff-status" :src="imgUrl+'publicicon/icon_memconfirm.png'" alt="">
                    <img v-if="item.status===3" class="staff-status" :src="imgUrl+'publicicon/icon_memquit.png'" alt="">
                    <img v-if="item.status===4" class="staff-status" :src="imgUrl+'publicicon/icon_dimission.png'" alt="">
                </div>
            </div>
            </checkbox-group>
        </div>
            </template>

            <app-wrapper-empty
              v-else
              title="暂无员工"
              :is-empty="$util.isEmpty(list.data)">
              <template slot="footer">
                <div class="jumpBtn" @click="addStaffPage">{{decodeURIComponent(option.tips)}}</div>
              </template>
            </app-wrapper-empty>

        <div class="footer_btn" v-if="!$util.isEmpty(list.data)">
          <div class="left_btn">
              <checkbox :checked="allChecked" color="#ffd11a" @click="changeCheck"/>
            全选<span class="des">（已选{{ alreadyNum }}人）</span>
          </div>
          <div class="affirm" @click="affirmBtn">确认</div>
        </div>
      </div>
    </div>

</template>

<script>
import AppWrapperEmpty from '@/components/App_wrapper_empty'
import { list } from '@/mixins'
import { getSelectStaff, delStaff } from '@/api/staffManage/index'
import StaffList from './components/staffList'
import { mapActions } from 'vuex'
// import AppCheckboxGroup from '@/components/App_checkbox/checkbox-group'
// import AppCheckbox from '@/components/App_checkbox/checkbox'
// import qs from 'qs'
// import { setTimeout } from 'timers'

export default {
	name: 'SelectStaff', // 员工选择
	mixins: [list],
	components: {
		AppWrapperEmpty,
		StaffList
		// AppCheckboxGroup,
		// AppCheckbox
	},
	watch: {
		alreadyNum(val) {
			this.allChecked = this.list.data.length == val
			// uni.showToast({
			// 	title: JSON.stringify(this.selArr) + this.allChecked,
			// 	icon: 'none',
			// 	duration: 3000
			// })
		}
	},
	computed: {
		alreadyNum() {
			if (this.$util.isEmpty(this.list.data)) return 0
			return this.selArr.length
		}
	},
	data() {
		return {
			showList: false,
			allChecked: false,
			option: {},
			imgUrl: this.$constant.imgUrl,
			selArr: [],
			selRelationArr: []
		}
	},
	onLoad(option) {
		console.log(option, '选择员工 option')
		this.option = option
		// console.log(decodeURIComponent(option.formData), 'decodeURIComponent(option.formData) 选择员工页')
		// console.log(JSON.parse(decodeURIComponent(option.formData)), 'JSON.parse(decodeURIComponent(option.formData)) 选择员工页')
		if (option.formData) {
			const formData = JSON.parse(decodeURIComponent(option.formData))
			if (formData.user_id_str) {
				this.selArr = formData.user_id_str.split(',')
			}
			this.option.formData = formData
		}
		const { title, imgUrl } = this.option
		if (title) {
			this.option.title = decodeURIComponent(title)
		}
		if (imgUrl) {
			this.option.imgUrl = decodeURIComponent(imgUrl)
		}
		this.init(this.selArr.length)
	},
	onPullDownRefresh() {
		this.resetList()
		this.init()
			.then(() => {
				uni.stopPullDownRefresh()
			})
	},
	onReachBottom() {
		if (this.list.finished) {
			uni.showToast({
				title: '没有更多了',
				icon: 'none'
			})
			return
		}
		if (this.list.loading) {
			return
		}
		this.init()
	},
	methods: {
		...mapActions(['setStaffIDList']),
		init(length) {
			// manage 员工管理页  team 推给团队
			const params = {
				api_type: this.option.filter === 'team' ? 'filter' : 'all',
				page: this.list.page,
				limit: (length && length > 6) ? length : 6
			}
			if (this.option.back_department_id) {
				params.department_id = this.option.back_department_id
			}
			return getSelectStaff(params).then((res) => {
				this.completes(res)
				if (this.selArr.length) {
					// this.list.data.forEach(item => {
					// 	this.selArr.forEach(subItem => {
					// 		if (!item.check) {
					// 			item.check = subItem == item.relation_id
					// 		}
					// 	})
					// })
					this.selArr = this.selArr.map(i => Number(i))
					this.changeStatus()
				} else {
					this.list.data = this.list.data.map(i => ({
						...i,
						check: false
				    }))
				}
			})
		},

		checkItem(e) {
			console.log(e, '选择多选框')
			this.selArr = e.detail.value.map(i => Number(i))
			if (this.selArr.length == 0) {
				this.list.data = this.list.data.map(i => ({
					...i,
					check: false
				}))
			} else {
				this.changeStatus()
			}
		},
		changeStatus() {
			const indexArr = []
			this.selArr.forEach(item => {
				const index = this.list.data.map(item => item.relation_id).indexOf(item)
				if (index != -1) {
					indexArr.push(index)
					this.list.data[index].check = true
				}
			})
			if (indexArr.length) {
				this.list.data.forEach((item, index) => {
					if (indexArr.indexOf(index) == -1) {
						item.check = false
					}
				})
			}
		},
		changeCheck() {
			this.allChecked = !this.allChecked
			this.list.data = this.list.data.map(i => ({
				...i,
				check: this.allChecked
			}))
			if (this.allChecked) {
				this.selArr = this.list.data.map(item => item.relation_id)
			} else {
				this.selArr = []
			}
		},
		affirmBtn() {
			if (this.$util.isEmpty(this.selArr)) {
				uni.showToast({
					title: '请选择员工',
					icon: 'none'
				})
				return
			}
			if (this.option.operate === 'del') {
				delStaff({ relation_ids: this.selArr.join(',') }).then((res) => {
					uni.showToast({
						title: '删除成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: `/pages/admin/staffManage/staffManage?department_id=${this.option.back_department_id}`
						})
					}, 500)
					return
				})
			} else if (this.option.operate === 'move') {
				const params = {
					relation_ids: this.selArr.join(','),
					department_id: 0,
					num: 1
				}
				uni.navigateTo({
					url: `/pages/admin/staffManage/selDepartment${this.commonJS.queryData(params)}`
				})
				return
			} else {
				let params = {
					...this.option,
					staff: this.selArr.join(','),
					formData: JSON.stringify(this.option.formData)
				}
				switch (this.option.fromPage) {
					case 'addTask':
						let relationArr = []
						this.list.data.forEach(item => {
							for (let i = 0; i < this.selArr.length; i++) {
								if (item.relation_id == this.selArr[i]) {
									relationArr.push(item.relation_user_id)
								}
							}
						})
						this.setStaffIDList(relationArr)
						uni.redirectTo({
				        	url: `/pages/getGuest/addTask${this.commonJS.queryData(params)}`
						})
						// uni.navigateBack()
						break
					case 'pushTeam':
					// console.log(params, '选择员工 --> 推给团队')
						let newSelArr = []
						this.list.data.forEach(item => {
							for (let i = 0; i < this.selArr.length; i++) {
								if (item.relation_id == this.selArr[i]) {
									newSelArr.push(item.relation_user_id)
								}
							}
						})
						this.setStaffIDList(newSelArr)
						// params.staff = newSelArr.join(',')
						uni.redirectTo({
				        	url: `/pages/getGuest/pushTeam${this.commonJS.queryData(params)}`
						})
						break
					case 'siteTeam':
					// console.log(params, '选择员工 --> 推给团队')
						uni.redirectTo({
				        url: `/pages/constructionSite/detail${this.commonJS.queryData(params)}`
						})
						break
					default:
						uni.navigateBack()
				}
			}
		},
		// updateCheck(checkInfo) {
		// 	this.list.data[checkInfo.index].check = checkInfo.check
		// },
		toDetail(item) {
			if (this.check == 'false') {
				// this.$router.push({
				//   name: 'Memberdetail',
				//   query: {
				//     relation_user_id: item.relation_user_id,
				//     user_id: item.relation_user_id
				//   }
				// })
			}
		},
		// 新增员工
		addStaffPage() {
			uni.navigateTo({
				url: `/pages/admin/staffManage/staffManage`
			})
		}
	}
}
</script>

<style lang="scss" scoped>
    .list {
        padding-bottom: 100px;
    }
    .van-popup.van-popup--bottom{
        background-color: #DDDDDD;
    }
    .jumpBtn {
        margin: 0 auto;
        display: block;
        color: #391b06;
        font-size: 28px;
        margin-top: 30px;
        border-radius: 30px;
        text-align: center;
        background: #ffd11a;
		width: 180px;
		height: 60px;
		line-height: 60px;
    }
    .staff-list_box {
        padding: 10px 30px;
        .staff-list {
            padding: 30px 20px;
            background-color: #FFFFFF;
            display: flex;
            align-items: center;
            box-shadow:0px 1px 6px 0px rgba(221,221,221,0.5);
            border-radius:20px;
            margin-top: 20px;
            overflow: hidden;
            position: relative;
            & > img {
                width: 120px;
                height: 120px;
                border-radius: 50%;
                margin-left: 20px;
            }
            & .staff-list_right {
                flex: 1;
                padding-left: 20px;
                & > h3 {
                    color: #333333;
                    font-weight: 600;
                    font-size: 34px;
                    margin-bottom: 20px;
                }
                & > div {
                    color: #666666;
                    font-weight: 400;
                    font-size: 24px;
                    line-height: 30px;
                }
            }
            & .staff-status {
                position: absolute;
                right: 0;
                top: 0;
                width: 90px;
                height: 90px;
                & > img{
                    width: 100%;
                    height: 100%;
                }
            }
            // & .staff-status {
            //     width: 180px;
            //     background-color: #09BB07;
            //     color: #FFFFFF;
            //     line-height: 45px;
            //     font-size:22px;
            //     text-align: center;
            //     position: absolute;
            //     right:-50px;
            //     top: 16px;
            //     transform-origin: 50% 50%;
            //     transform: rotate(45deg);
            //     &.no_status {
            //         color: #3A1B04;
            //         background-color: #FFD11A;
            //     }
            // }
        }
    }
    .footer_btn {
        width: 100%;
        height:100px;
        background:rgba(255,255,255,1);
        box-shadow:0px -3px 10px 0px rgba(0, 0, 0, 0.1);
        position: fixed;
        bottom: 0;
        display: flex;
        .left_btn {
            flex: 1;
            display: flex;
            align-items: center;
            padding-left: 30px;
            font-size: 30px;
            & .des {
                font-size: 24px;
                font-weight:400;
                color: #999999;
            }
        }
        & .affirm {
            line-height: 98px;
            width: 264px;
            background-color: #FFD11A;
            color: #3A1B04;
            font-weight: 400;
            text-align: center;
            font-size: 32px;

        }
    }
</style>
